#include <iostream>
#include "TcpServer.hpp"
#include "Sock.hpp"
#include "Pro_to_col.hpp"
#include <memory>
#include<signal.h>
using namespace tcp_server;
using namespace ser_and_dser;
static void Usage(const std::string &proc)
{
    std::cout << "\nUsage: " << proc << "port\n";
}
static Response count_result(Request &req)
{
    Response result(0, 0);
    switch (req._op)
    {
    case '+':
        result._res = req._x + req._y;
        break;
    case '-':
        result._res = req._x - req._y;
        break;
    case '*':
        result._res = req._x * req._y;
        break;
    case '/':
        if (req._y == 0)
        {
            result._flag = 1;
        }
        else
            result._res = req._x / req._y;
        break;
    case '%':
        if (req._y == 0)
        {
            result._flag = 2;
        }
        else
            result._res = req._x % req._y;
        break;
    default:
        result._flag = 3;
        break;
    }
    return result;
}
void calculator(int sock)
{
    std:: string inbuffer;
    while (true)
    {
        bool res = Recv(sock,&inbuffer);
        if (!res)
        {
            break;
        } 
        std::string package = Decode(inbuffer);
        if(package.empty())
            continue;
        logMessage(NORMAL,"%s",package.c_str());
        Request req;
        req.Deserialize(package);
        Response result = count_result(req);
        std::string str = result.Serlize();
        //编码
        str = Encode(str);
        Send(sock, str);
    }
   
}
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }
    //忽略掉信号

    signal(SIGPIPE,SIG_IGN);
    std::unique_ptr<TcpServer> server(new TcpServer(atoi(argv[1])));
    server->BindServer(calculator);
    server->Start();

    // Request req(100, 200, '+');
    // std::string s = req.Serialize();
    // std::cout << s << std::endl;
    return 0;
}